package com.panda.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panda.takeaway.auth.dto.SignResult;
import com.panda.takeaway.auth.util.SecurityUtil;
import com.panda.takeaway.dao.*;
import com.panda.takeaway.entity.bo.LoginBo;
import com.panda.takeaway.entity.bo.PwdBo;
import com.panda.takeaway.entity.bo.UserLoginBo;
import com.panda.takeaway.entity.dto.CommonResult;
import com.panda.takeaway.entity.po.Address;
import com.panda.takeaway.entity.po.Role;
import com.panda.takeaway.entity.po.User;
import com.panda.takeaway.entity.po.UserRole;
import com.panda.takeaway.entity.vo.UserInfoVo;
import com.panda.takeaway.service.UserService;
import com.panda.takeaway.service.constant.AccountStatusConstant;
import com.panda.takeaway.service.constant.AddressDefaultConstant;
import com.panda.takeaway.service.constant.RoleConstant;
import com.panda.takeaway.service.constant.SexConstant;
import com.panda.takeaway.util.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wjh
 * @date 2021/8/7 9:35
 * @Package com.panda.takeaway.service
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private PhotoMapper photoMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private SecurityUtil securityUtil;

    @Override
    public CommonResult<UserLoginBo> login(LoginBo loginBo) {
        UserLoginBo userLoginBo = new UserLoginBo();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("telephone", loginBo.getTelephone());
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            return CommonResult.operateFailWithMessage("登录失败，该手机号尚未注册！");
        }

        if (!user.getPassword().equals(MD5Util.getMD5String(loginBo.getPassword()))) {
            return CommonResult.operateFailWithMessage("登录失败，密码错误！");
        }

        //账号被封禁，给出解封时间
        if (user.getAccountStatus().equals(AccountStatusConstant.DISABLE) && user.getValidTime().after(new Timestamp(System.currentTimeMillis()))) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return CommonResult.operateFailWithMessage("该账号已被禁用！解封时间：" + simpleDateFormat.format(new Date(user.getValidTime().getTime())));
        }

        //可以解封账号了
        if (user.getAccountStatus().equals(AccountStatusConstant.DISABLE) && user.getValidTime().before(new Timestamp(System.currentTimeMillis()))) {
            User userAble = new User();
            userAble.setId(user.getId());
            userAble.setAccountStatus(AccountStatusConstant.ABLE);
            userMapper.updateById(userAble);
        }

        //密码不可以返回
        user.setPassword(null);
        userLoginBo.setUser(user);

        //查询用户权限
        List<String> permissionList = permissionMapper.listPermissionsByUserId(user.getId());
        userLoginBo.setPermissionList(permissionList);
        //查询用户具有的角色
        userLoginBo.setRoleList(roleMapper.listRoleByUserId(user.getId()));

        SignResult signResult = securityUtil.login(user.getId().toString(), permissionList, user);
        if (signResult.isSuccess()) {
            userLoginBo.setToken(signResult.getToken());
            userLoginBo.setExpireAt(signResult.getExpireAt());
            userLoginBo.setPermissionList(permissionList);
            return CommonResult.operateSuccess(userLoginBo);
        }

        return CommonResult.operateFailWithMessage("系统繁忙，登陆失败，请稍后重试！");
    }

    @Override
    public CommonResult<UserInfoVo> queryInfoById(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.operateFailWithMessage("查询失败,用户id不存在！");
        }

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setUserId(user.getId());
        userInfoVo.setTelephone(user.getTelephone());
        userInfoVo.setName(user.getName());
        if (SexConstant.MAN_NUM.equals(user.getSex())) {
            userInfoVo.setSex(SexConstant.MAN);
        } else {
            userInfoVo.setSex(SexConstant.WOMAN);
        }
        userInfoVo.setPhotoUrl(photoMapper.selectById(user.getPhotoId()).getUrl());
        return CommonResult.operateSuccess(userInfoVo);
    }

    @Override
    public CommonResult<?> updateInfoById(UserInfoVo userInfoVo) {
        User user = new User();
        user.setId(userInfoVo.getUserId());
        user.setName(userInfoVo.getName());
        if (userInfoVo.getSex().equals(SexConstant.MAN)) {
            user.setSex((byte) 0);
        } else {
            user.setSex((byte) 1);
        }
        if (userMapper.updateById(user) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage("系统繁忙，修改个人信息失败！");
    }

    @Override
    public CommonResult<?> register(User user) {
        Assert.notNull(user, "user对象为null");
        Map<String, Object> map = new HashMap<>();
        user.setPassword(MD5Util.getMD5String(user.getPassword()));
        map.put("telephone", user.getTelephone());
        if (userMapper.selectByMap(map).size() > 0) {
            return CommonResult.operateFailWithMessage("该手机号已经注册过了");
        }

        if (userMapper.insert(user) > 0) {
            return CommonResult.operateSuccess();
        }

        return CommonResult.operateFailWithMessage("系统繁忙，请稍后重试！");
    }

    @Override
    public CommonResult<?> addAddress(Address address) {
        Assert.notNull(address, "address对象为null");

        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", address.getUserId());
        List<Address> addressList = addressMapper.selectList(wrapper);

        if (addressList.size() > 0) {
            address.setDefaultAddress(AddressDefaultConstant.NOT_DEFAULT);
        } else {
            address.setDefaultAddress(AddressDefaultConstant.DEFAULT);
        }


        if (addressMapper.insert(address) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage("系统繁忙，添加失败，请稍后重试！");
    }

    @Override
    public CommonResult<List<Address>> queryAddressByUserId(Long userId) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<Address> addressList = addressMapper.selectList(wrapper);
        if (addressList.size() == 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateSuccess(addressList);
    }

    @Override
    public CommonResult<?> deleteAddressById(Long id) {
        if (addressMapper.deleteById(id) > 0) {
            return CommonResult.operateSuccess();
        }

        return CommonResult.operateFailWithMessage("系统繁忙，删除失败，请稍后重试！");
    }

    @Override
    public CommonResult<?> updateAddressToDefaultById(Map<String, Long> map) {
        Address address = new Address();
        address.setDefaultAddress(AddressDefaultConstant.NOT_DEFAULT);
        address.setId(map.get("userId"));
        addressMapper.updateById(address);
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", map.get("userId"));
        wrapper.eq("id", map.get("addressId"));

        address.setDefaultAddress(AddressDefaultConstant.DEFAULT);
        //id不修改
        address.setId(null);
        if (addressMapper.update(address, wrapper) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage("系统繁忙，修改失败，请稍后重试！");
    }

    @Override
    public CommonResult<?> updatePassword(PwdBo pwdBo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", pwdBo.getUserId());
        wrapper.eq("password", MD5Util.getMD5String(pwdBo.getOldPwd()));
        if (userMapper.selectOne(wrapper) == null) {
            return CommonResult.operateFailWithMessage("原密码错误！");
        }

        User user = new User();
        user.setId(pwdBo.getUserId());
        user.setPassword(MD5Util.getMD5String(pwdBo.getNewPwd()));
        if (userMapper.updateById(user) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage("系统繁忙，请稍后重试！");
    }

    @Override
    public CommonResult<?> addMerchant(LoginBo loginBo) {
        //校验是否为本人操作
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("telephone", loginBo.getTelephone());
        wrapper.eq("password", MD5Util.getMD5String(loginBo.getPassword()));
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
        System.out.println(SecurityUtil.getUserId());
        if (user == null) {
            return CommonResult.operateFailWithMessage("请输入正确的手机号码和密码！");
        } else {
            if (!SecurityUtil.getUserId().equals(user.getId())) {
                return CommonResult.operateFailWithMessage("请确认这是您的账号！");
            }
        }

        QueryWrapper<Role> roleWrapper = new QueryWrapper<>();
        roleWrapper.eq("name", RoleConstant.MERCHANT);
        Role role = roleMapper.selectOne(roleWrapper);

        //入驻商家
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        if (userRoleMapper.insert(userRole) > 0) {
            return CommonResult.operateSuccess();
        }

        return CommonResult.operateFailWithMessage("系统繁忙，请稍后重试！");
    }

}
